import type { CustomRequestOptions } from '@/interceptors/request'
import { checkStatus, CODE_SUCCESS, CODE_TOKEN_FAIL } from '@/api/helper'

export function http<T>(options: CustomRequestOptions) {
  // 1. 返回 Promise 对象
  return new Promise<IResData<T>>((resolve, reject) => {
    uni.request({
      ...options,
      dataType: 'json',
      // #ifndef MP-WEIXIN
      responseType: 'json',
      // #endif
      // 响应成功
      success(res) {
        const { data } = res

        // 状态码 2xx，参考 axios 的设计
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 登录失效
          if (String((data as IResData<T>).code) === CODE_TOKEN_FAIL) {
            // 清理用户信息
            // const userStore = useUserStore()
            // userStore.clearUserInfo()

            // 跳转到登录页
            uni.navigateTo({ url: '/pages/login/login' })
            uni.showToast({
              icon: 'none',
              title: (data as IResData<T>).msg || '登录失效，请重新登录',
            })
            return reject(data)
          }

          // 全局错误信息拦截
          if (
            (data as IResData<T>).code
            && (data as IResData<T>).code?.toString() !== CODE_SUCCESS
          ) {
            !options.hideErrorToast
            && uni.showToast({
              icon: 'none',
              title: (data as IResData<T>).msg || '请求错误',
            })
            return reject(data)
          }

          // 成功请求
          resolve(data as IResData<T>)
        }
        else {
          // 根据服务器响应的错误状态码，做不同的处理
          checkStatus(res.statusCode, (data as IResData<T>)?.msg)
          reject(res)
        }
      },
      // 响应失败
      fail(err) {
        // 请求超时 && 网络错误单独判断
        if (err.errMsg && err.errMsg.includes('timeout')) {
          uni.showToast({ icon: 'none', title: '请求超时！请您稍后重试' })
        }
        else if (err.errMsg && err.errMsg.includes('fail')) {
          uni.showToast({ icon: 'none', title: '网络错误！请您稍后重试' })
        }
        else {
          uni.showToast({
            icon: 'none',
            title: '网络错误，换个网络试试',
          })
        }
        reject(err)
      },
    })
  })
}

/**
 * GET 请求
 * @param url 后台地址
 * @param query 请求query参数
 * @param header 请求头，默认为json格式
 * @returns
 */
export function httpGet<T>(
  url: string,
  query?: Record<string, any>,
  header?: Record<string, any>,
  options?: Partial<CustomRequestOptions>,
) {
  return http<T>({
    url,
    query,
    method: 'GET',
    header,
    ...options,
  })
}

/**
 * POST 请求
 * @param url 后台地址
 * @param data 请求body参数
 * @param query 请求query参数，post请求也支持query，很多微信接口都需要
 * @param header 请求头，默认为json格式
 * @returns
 */
export function httpPost<T>(
  url: string,
  data?: Record<string, any>,
  query?: Record<string, any>,
  header?: Record<string, any>,
  options?: Partial<CustomRequestOptions>,
) {
  return http<T>({
    url,
    query,
    data,
    method: 'POST',
    header,
    ...options,
  })
}
/**
 * PUT 请求
 */
export function httpPut<T>(
  url: string,
  data?: Record<string, any>,
  query?: Record<string, any>,
  header?: Record<string, any>,
  options?: Partial<CustomRequestOptions>,
) {
  return http<T>({
    url,
    data,
    query,
    method: 'PUT',
    header,
    ...options,
  })
}

/**
 * DELETE 请求（无请求体，仅 query）
 */
export function httpDelete<T>(
  url: string,
  query?: Record<string, any>,
  header?: Record<string, any>,
  options?: Partial<CustomRequestOptions>,
) {
  return http<T>({
    url,
    query,
    method: 'DELETE',
    header,
    ...options,
  })
}

http.get = httpGet
http.post = httpPost
http.put = httpPut
http.delete = httpDelete
